<?php namespace App\Services\Wechat;

use App\Doctors;
use App\Hospital;
use App\Orders;
use App\Questions;
use App\Referral;
use App\User;
use App\UserInfo;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Log;

class WechatModelMsg
{
    public static function sendAppointMsg($billNum,$url = '#'){

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($billNum)->whereIspay(1)->first();

        if(!$thatOrder)
            return false;

        /** @var User $thatUser */
        $thatUser = User::find($thatOrder->user_id);

        if(!$thatUser)
            return false;

        $app = app("wechat");
        $notice = $app->notice;

        $userId = $thatUser->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $userinfo = $thatUser->userInfo;
        $sex = '未设置';
        if($userinfo && $userinfo->sexual !== 0){
            switch($userinfo->sexual){
                case 1:
                    $sex = '男';
                    break;
                case 2:
                    $sex = '女';
                    break;
            }
        }

        /** @var Doctors $thatDoctor */
        $thatDoctor = Doctors::whereUserId($thatOrder->doctor_id)->first();

        $hospital = null;
        if($thatDoctor){
            /** @var Hospital $hospital */
            $hospital = Hospital::whereId($thatDoctor->hospital_id)->first();
        }

        $templateId = 'lMxFZ_Q7hhkHok6YXgbg15EKJqeN6hlMnAMeH466QAQ';
        $color = '#FF0000';
        $data = array(
            "first"         => "您好，您在桂林名医网预约成功。",
            "patientName"   => $thatOrder->patient_name,
            "patientSex"    => $sex,
            "hospitalName"  => $hospital?$hospital->name : '[未知]',
            'department'    => $thatDoctor->subject,
            'doctor'        => $thatDoctor->doc_name,
            'seq'           => $billNum,
            'remark'        => "如果您有任何问题请联系桂林名医网，电话：13077664995/13077610193（可致电／可加微信）",
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }

    public static function sendMsgToDoctor($billNum,$url = '#'){

        /** @var Orders $thatOrder */
        $thatOrder = Orders::whereOrderNum($billNum)->whereIspay(1)->first();

        if(!$thatOrder)
            return false;

        /** @var User $thatUser */
        $thatUser = User::find($thatOrder->user_id);

        $doctor = Doctors::whereUserId($thatOrder->doctor_id)->first();

        if(!$doctor)
            return false;

        $type = '';
        switch($thatOrder->type){
            case 'face':
                $type = '面诊';
                break;
            case 'appoint':
                $type = '门诊';
                break;
        }

        $dayType = '';
        switch($thatOrder->bespoke_slot){
            case 'am':
                $dayType = '上午';
                break;
            case 'pm':
                $dayType = '下午';
                break;
        }

        /** @var User $thatUserDoc */
        $thatUserDoc = User::find($thatOrder->doctor_id);
        if(!$thatUserDoc)
            return false;

        $userId = $thatUserDoc->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = 'I_z8G5oUSaT53FwvDrdKiJvUSES6vAeo9cDijxWs5a0';
        $data = array(
            "first"    => "您有一个新的［".$type."］预约",
            "keyword1" => $thatOrder->patient_name,
            "keyword2" => date('Y年m月d日',strtotime($thatOrder->bespoke_time)).$dayType,
            "keyword3" => $thatOrder->patient_phone,
            "keyword4" => "暂无",
            "keyword5" => $type,
            "remark"   => '点击“详情”查看预约资料',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }

    public static function sendQuestionMsgToDoctor(Questions $questionModel,$url = '#'){

        $thatDoctor = User::whereId($questionModel->doctor_id)->first();

        if(!$thatDoctor)
            return false;

        $userId = $thatDoctor->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = 'Bbl66A2eF2VwlBMFPcfytwTQKvRVzyNJ7T1KLC8ttPY';
        $data = array(
            "first"    => "您收到患者一个新的提问",
            "keyword1" => date('Y-m-d H:i:s',time()),
            "keyword2" => mb_substr($questionModel->question,0,10).'...',
            "remark"   => '点击“详情”查看问题内容',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;

    }

    public static function sendAnswerMsgToUser(Questions $questionModel,$url = '#'){
        $thatUser = User::whereId($questionModel->user_id)->first();

        if(!$thatUser)
            return false;

        $userId = $thatUser->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = 'Qi3_dLlb7SgMdc_4GMf2EHoQ7xBMPU7SgxrJAklSV5s';
        $data = array(
            "first"    => "您好！您的问题得到了医生的反馈",
            "keyword1" => mb_substr($questionModel->question,0,10).'...',
            "keyword2" => date('Y-m-d H:i:s',time()),
            "remark"   => '点击“详情”查看回答内容',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }

    public static function sendReferralsMsgToDoctor(Referral $referral,$hospitalId=0,$url = '#'){
        /** @var User $thatUser */
        $thatUser = User::whereId($referral->user_id)->first();
        if(!$thatUser)
            return false;

        /** @var User $doctor */
        $doctor = User::whereId($referral->d_user_id)->first();
        if(!$doctor)
            return false;

        /** @var User $receiveDoctor */
        $receiveDoctor = User::whereId($referral->dr_user_id)->first();
        if(!$receiveDoctor)
            return false;

        $userInfo       = $thatUser->userInfo;
        /** @var Doctors $docInfo */
        $docInfo        = Doctors::whereUserId($doctor->id)->first();
        /** @var Doctors $receiveDocInfo */
        $receiveDocInfo = Doctors::whereUserId($doctor->id)->first();

        /** @var Hospital $hospital */
        $hospital = Hospital::whereId($hospitalId)->first();

        $userId = $receiveDoctor->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = '_qgeKdq0ywIF24A6-WSZ7sqjahRzDA1uSB-XuIpSFjo';
        $data = array(
            "first"    => "收到一个新转诊申请订单",
            "keyword1" => $userInfo ? $userInfo->realname."[".$userInfo->phone."]" : "未知",
            "keyword2" => $docInfo ? $docInfo->doc_name : "未知",
            "keyword3" => $receiveDocInfo ? $receiveDocInfo->doc_name : "未知",
            "keyword4" => "订单来自【".$hospital ? $hospital->name : "未知"."】",
            "remark"   => '点击“详情”对订单进行确认',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }

    public static function sendPayMsgToUser(Referral $referral,$url = "#"){
        /** @var User $thatUser */
        $thatUser = User::whereId($referral->user_id)->first();
        if(!$thatUser)
            return false;

        /** @var UserInfo $thatUserInfo */
        $thatUserInfo = UserInfo::whereUserId($thatUser->id)->first();

        /** @var User $doctor */
        $doctor = User::whereId($referral->d_user_id)->first();
        if(!$doctor)
            return false;

        $doctorInfo = Doctors::whereUserId($doctor->id)->first();

        $doctorHospital = "";
        if($doctorInfo) {
            $thatHospital = Hospital::whereId($doctorInfo->hospital_id)->first();
            if($thatHospital)
                $doctorHospital = $thatHospital->name;
        }

        /** @var User $receiveDoctor */
        $receiveDoctor = User::whereId($referral->dr_user_id)->first();
        if(!$receiveDoctor)
            return false;

        $receiveDoctorHospital = '';
        /** @var Doctors $receiveDocInfo */
        $receiveDocInfo = Doctors::whereUserId($receiveDoctor->id)->first();
        if($receiveDocInfo){
            $thatHospital = Hospital::whereId($referral)->first();
            if($thatHospital)
                $receiveDoctorHospital = $thatHospital->name;
        }

        $userId = $thatUser->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = '3BnGORhypjfkPnglghKtEKmuqgtM9E88svKQ2WKcnGQ';
        $data = array(
            "first"    => $receiveDocInfo ? $receiveDocInfo->doc_name : '' ."医生已经确认转诊，请支付转诊费用",
            "keyword1" => $thatUserInfo ? $thatUserInfo->realname : '[未知]',
            "keyword2" => $doctorHospital."【转】".$receiveDoctorHospital,
            "keyword3" => $referral->amount,
            "remark"   => '点击“详情”对转诊订单进行支付',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }

    public static function sendComfirmMsgToDoctor(Referral $referral,$url = "#"){
        /** @var User $thatUser */
        $thatUser = User::whereId($referral->user_id)->first();
        if(!$thatUser)
            return false;

        /** @var UserInfo $thatUserInfo */
        $thatUserInfo = UserInfo::whereUserId($thatUser->id)->first();

        /** @var User $doctor */
        $doctor = User::whereId($referral->d_user_id)->first();
        if(!$doctor)
            return false;

        $doctorInfo = Doctors::whereUserId($doctor->id)->first();

        $doctorHospital = "";
        if($doctorInfo) {
            $thatHospital = Hospital::whereId($doctorInfo->hospital_id)->first();
            if($thatHospital)
                $doctorHospital = $thatHospital->name;
        }

        /** @var User $receiveDoctor */
        $receiveDoctor = User::whereId($referral->dr_user_id)->first();
        if(!$receiveDoctor)
            return false;

        $receiveDoctorHospital = '';
        /** @var Doctors $receiveDocInfo */
        $receiveDocInfo = Doctors::whereUserId($receiveDoctor->id)->first();
        if($receiveDocInfo){
            $thatHospital = Hospital::whereId($referral)->first();
            if($thatHospital)
                $receiveDoctorHospital = $thatHospital->name;
        }

        $userId = $doctor->openid;
        if(!$userId || is_null($userId) || $userId == '')
            return false;

        $app = app("wechat");
        $notice = $app->notice;
        $templateId = 'e1RCv0aNVT5I2O8GFt5ANK0UuhqTSvS_FznWCamglfA';
        $data = array(
            "first"    => "您好， 您发送的转诊请求已被接受",
            "keyword1" => $thatUserInfo->realname,
            "keyword2" => $receiveDoctorHospital."-".$receiveDocInfo->doc_name,
            "keyword3" => "无",
            "keyword4" => "".date("Y-m-d H:i:s",time()),
            "remark"   => '请及时联系病人并告知尽快支付转诊费用！',
        );
        $result = $notice->uses($templateId)->withUrl($url)->andData($data)->andReceiver($userId)->send();

        if($result->errmsg == 'ok')
            return true;
        else
            return $result->errmsg;
    }
}